//
//  MostNewTableview.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/28.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "MostNewTableview.h"
#import "AFNetworking.h"
#import "NewestTopicTableViewCell.h"
#import "NewsetModel.h"
#import "NewestTableViewCell.h"
#import "AppDelegate.h"
#import "RecordViewController.h"
#import "DCPicScrollView.h"
#import "DCWebImageManager.h"
#import "UIImageView+WebCache.h"
#define kDeviceHeight [UIScreen mainScreen].bounds.size.height
#define kDeviceWidth  [UIScreen mainScreen].bounds.size.width

@interface MostNewTableview ()<UITableViewDelegate, UITableViewDataSource,MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    MJRefreshFooterView *fotter;
    DCPicScrollView *baner;
    NSString *_filePath;
    NSArray *banerArray;
    UIImageView *banerButton;
}
@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *attenArray;
@end

@implementation MostNewTableview
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.attenArray = [[NSMutableArray alloc] init];
        [self createTableview];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"MostNew"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadNewestDataWithResponseObject:content pag:1];
            page = 1;
        } else {
        }
        [_header beginRefreshing];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(topicPublish:) name:@"topicPublish" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAttentionArray:) name:@"changeAttenArray" object:nil];
    }
    return self;
}
- (void)topicPublish:(NSNotification *)notification
{
    [AppDelegate shareDelegate].startTag = @"话#题";
    NSString *str = notification.object;//_topicArray[indexPath.row];
    [AppDelegate shareDelegate].topicString = str;
    RecordViewController *record = [[RecordViewController alloc] initWithType:[AppDelegate shareDelegate].startTag detile:[AppDelegate shareDelegate].topicString];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:record];
    [[AppDelegate shareDelegate].window.rootViewController presentViewController:nav animated:YES completion:nil];
}
- (void)changeAttentionArray:(NSNotification *)notification
{
//    NSLog(@"%@",_attenArray);
    NewestTableViewCell *cell = notification.object;
    NSIndexPath *path = [self.tableview indexPathForCell:cell];
    NewsetModel *model = _attenArray[path.row];
    NSString *uname = [model.user valueForKey:@"username"];
    for (int i = 0; i < _attenArray.count; i++) {
        if ([_attenArray[i] isKindOfClass:[NewsetModel class]]) {
             NewsetModel *_model = _attenArray[i];
            if ([[_model.user valueForKey:@"username"] isEqualToString:uname] && [[_model.user valueForKey:@"follow"] integerValue] == 0) {
                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:_model.user];
                [dic setValue:[NSNumber numberWithInt:1] forKey:@"follow"];
                _model.user = dic;
                [_attenArray replaceObjectAtIndex:i withObject:_model];
            }
        }
    }
//    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:model.user];
    [_tableview reloadData];
}
- (void)createTableview
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [self addSubview:_tableview];
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    _header = [MJRefreshHeaderView header];
    _header.scrollView = _tableview;
    _header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _tableview;
    fotter.delegate = self;
}
- (void)createTableViewHeader:(NSArray *)array;
{
    
//    NSArray *UrlStringArray = [NSArray arrayWithObjects:@"http://p1.qqyou.com/pic/UploadPic/2013-3/19/2013031923222781617.jpg", @"http://p1.qqyou.com/pic/UploadPic/2013-3/19/2013031923222781617.jpg",
//        @"http://cdn.duitang.com/uploads/item/201409/27/20140927192649_NxVKT.thumb.700_0.png",nil];
    NSMutableArray *urlArray = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in array) {
        NSString *url = [dic valueForKeyPath:@"image"];
        [urlArray addObject:url];
    }
    if (urlArray.count > 1) {
        if (!baner) {
            baner = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, self.frame.size.width, (self.frame.size.width) * 0.40) WithImageUrls:urlArray];
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, baner.frame.size.height)];
            view.backgroundColor = [UIColor whiteColor];
//            [view addSubview:baner];
            _tableview.tableHeaderView = baner;
        }
        baner.placeImage = [UIImage imageNamed:@"place.png"];
        
        //图片被点击事件,当前第几张图片被点击了,和数组顺序一致
        
        [baner setImageViewDidTapAtIndex:^(NSInteger index) {
            printf("第%zd张图片\n",index);
            NSNumber *type = [array[index] valueForKey:@"type"];
            switch (type.intValue) {
                case 1://作品
                {
                    NSString *workID = [array[index] valueForKey:@"detail"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:workID];
                }
                    break;
                case 2://话题
                {
                    NSString *topic = [array[index] valueForKey:@"detail"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"searchTopic" object:[NSString stringWithFormat:@"#%@#", topic]];
                }
                    break;
                default:
                    break;
            }
        }];
        
        //default is 2.0f,如果小于0.5不自动播放
        baner.AutoScrollDelay = 5.0f;
        //    picView.textColor = [UIColor redColor];
        //下载失败重复下载次数,默认不重复,
        [[DCWebImageManager shareManager] setDownloadImageRepeatCount:1];
        //图片下载失败会调用该block(如果设置了重复下载次数,则会在重复下载完后,假如还没下载成功,就会调用该block)
        //error错误信息
        //url下载失败的imageurl
        [[DCWebImageManager shareManager] setDownLoadImageError:^(NSError *error, NSString *url) {
            NSLog(@"%@",error);
        }];
    } else {
        if (!banerButton) {
            banerButton = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, self.frame.size.width - 30, (self.frame.size.width - 30) * 0.40)];
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, banerButton.frame.size.height)];
            view.backgroundColor = [UIColor whiteColor];
            [view addSubview:banerButton];
            banerButton.userInteractionEnabled = YES;
            _tableview.tableHeaderView = view;
        }
        [banerButton setImageWithURL:[NSURL URLWithString:[urlArray firstObject]] placeholderImage:nil];
        UITapGestureRecognizer *recognaizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onlyOneBannerTap:)];
        [banerButton addGestureRecognizer:recognaizer];
    }
}
- (void)onlyOneBannerTap:(UITapGestureRecognizer *)recognaizer
{
    NSNumber *type = [banerArray[0] valueForKey:@"type"];
    switch (type.intValue) {
        case 1://作品
        {
            NSString *workID = [banerArray[0] valueForKey:@"detail"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:workID];
        }
            break;
        case 2://话题
        {
            NSString *topic = [banerArray[0] valueForKey:@"detail"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"searchTopic" object:[NSString stringWithFormat:@"#%@#", topic]];
        }
            break;
        default:
            break;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _attenArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_attenArray.count > 0) {
        if ([_attenArray[indexPath.row] isKindOfClass:[NewsetModel class]]) {
            NewsetModel *model = _attenArray[indexPath.row];
            if (model.tags.count > 0) {
                if ([UIScreen mainScreen].bounds.size.height > 667) {
                    return 0.42 * [UIScreen mainScreen].bounds.size.height;
                } else {
                    return 0.4136 * [UIScreen mainScreen].bounds.size.height;
                }
            } else {
                if ([UIScreen mainScreen].bounds.size.width == 320) {
                    return 0.41 * [UIScreen mainScreen].bounds.size.height;
                } else if ([UIScreen mainScreen].bounds.size.height == 667) {
                    return 0.41 * [UIScreen mainScreen].bounds.size.height;
                } else {
                    return 0.42 * [UIScreen mainScreen].bounds.size.height;
                }
            }
        } else {
            return 230;
        }
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_attenArray.count > 0 && [_attenArray[indexPath.row] isKindOfClass:[NSArray class]]) {
         static NSString *cellIdentifier = @"topicCell";
        NewestTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[NewestTopicTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier topicArray:_attenArray[indexPath.row]];
        }
//        cell.topicArray = [NSArray arrayWithArray:];
        return cell;
    } else {
        static NSString *cellIdentifier1 = @"cell1";
        NewestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
        if (cell == nil) {
            cell = [[NewestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1];
        }
        [cell.tagView removeFromSuperview];
        if (_attenArray.count > 0) {
            cell.model = _attenArray[indexPath.row];
        cell.tagView = [[groundTagsView alloc]initWithFrame:CGRectZero];
        [cell.tagView createTagView:cell.model.tags];
        [cell addSubview:cell.tagView];
        }
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_attenArray[indexPath.row] isKindOfClass:[NSArray class]]) {
        
    } else {
        NewsetModel *mod = _attenArray[indexPath.row];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:mod.id];
    }
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_attenArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    
}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/newest?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadNewestDataWithResponseObject:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [refreshView endRefreshing];
    }];
}
- (void)reloadNewestDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    for (NSDictionary *dict in dic) {
        NewsetModel *model = [[NewsetModel alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        NewsetModel *oldModel = [_attenArray lastObject] ;
        if (![model.id isEqualToString:oldModel.id]) {
            [_attenArray addObject:model];
        }
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            fotter.hidden = YES;
        }
        if (pag == 1) {
            NSInteger topicnum = [[meta valueForKey:@"topicnum"] integerValue];
            [_attenArray insertObject:[meta valueForKey:@"topic"] atIndex:topicnum];
            if ([meta objectForKey:@"banner"]) {
                banerArray = [meta objectForKey:@"banner"];
                [self createTableViewHeader:banerArray];
            } else {
                
            }
        }
    }
    _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [_tableview reloadData];
}
#pragma mark -
- (CGFloat)heightForText:(NSString *)text
{
    CGSize size = CGSizeMake(kDeviceWidth - 59, 2000);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:12.0f] forKey:NSFontAttributeName];
    CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return frame.size.height;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
